package cron

import (
	"cloudops/src/pbms"
	"context"
	"go.uber.org/zap"
	"k8s.io/apimachinery/pkg/util/wait"
	"time"
)

// JobExecManager 任务执行结果上报
func (c *CronManager) JobExecManager(ctx context.Context) error {
	go wait.UntilWithContext(ctx, c.RunTaskReport, time.Duration(c.Client.Sc.JobExecC.RunIntervalSeconds)*time.Second)
	<-ctx.Done()
	c.Client.Sc.Logger.Info("收到退出信号 RunTaskReport 退出")
	return nil
}

// RunTaskReport 任务执行结果上报
func (c *CronManager) RunTaskReport(ctx context.Context) {
	conn, err := c.Client.Pool.Get()
	if err != nil {
		c.Client.Sc.Logger.Error("计划任务-grpc池中获取连接失败",
			zap.Error(err))
		return
	}
	defer conn.Close()

	client := pbms.NewJobExecClient(conn.Value())
	ctx, cancel := c.Client.GenTwContext()
	defer cancel()

	// 获取结果
	taskResults := c.TaskManager.GetResults()
	// grpc上报
	resp, err := client.TaskReport(ctx, &pbms.TaskReportRequest{
		Hostname: c.Client.Sc.HostName,
		Ip:       c.Client.Sc.LocalIp,
		Results:  taskResults,
	})
	if err != nil {
		c.Client.Sc.Logger.Error("计划任务-任务执行结果上报失败",
			zap.Error(err))
		return
	}
	c.Client.Sc.Logger.Info("计划任务-任务执行结果上报成功",
		zap.Any("待分配任务的新数量", len(resp.Tasks)),
		zap.Any("已收到的结果", resp.ReceivedTaskIds))

	// 分配任务
	c.TaskManager.AssignTask(resp)
}
